"""
@author: shaoshuai
@file :shop_interface.py
@time: 2021/12/16 18:36
"""
from db import db_handler
from lib import common

# 根据不同的接口类型转入不同的日志对象
shop_logger = common.get_logger(log_type='shop')


# 商品支付接口
def shopping_interface(login_user,shop_car):
    # 打印用户余额
    user_dic = db_handler.select(login_user)

    # 1) 计算消费总额
    # {‘商品名称’：[]}
    cost = 0
    for price_number in shop_car.values():
        price,number = price_number

        cost += (price * number)

    # 2) 导入银行接口
    from interface import bank_interface

    # 逻辑校验成功后，再调用银行接口的支付接口
    flag = bank_interface.pay_interface(login_user,cost)
    if flag:
        msg = f'用户：[{login_user}] 支付[{cost}元]成功！！'
        shop_logger.info(msg)
        return True, msg

    return False, f"支付失败，还剩余额为：[{user_dic['balance']}元]"

# 保存购物车接口
def save_shop_car_interface(login_user,shop_car):
    user_dic = db_handler.select(login_user)
    if shop_car:

        user_dic['shop_car'] = shop_car
        # 保存数据
        db_handler.save(user_dic)

        msg = f"当前购物车保存完成: [{user_dic['shop_car']}]"
        shop_logger.info(msg)
        return True, msg

    msg = f'购物车是空的，不能保存购物车，请重新输入！'
    return False, msg

# 查看购物车接口
def check_shopping_car_interface(login_user):
    user_dic = db_handler.select(login_user)

    return user_dic['shop_car']

# 清空购物车接口
def clean_shop_car_interface(login_user):
    # 查看当前用户的数据
    user_dic = db_handler.select(login_user)
    shop_car = user_dic['shop_car']
    if shop_car:
        # {‘商品名称’：[]}
        print('当前购物车为：',shop_car)
        cost = 0
        for price_number in shop_car.values():
            price,number = price_number

            cost += (price * number)

        # 2) 导入银行接口
        from interface import bank_interface

        # 逻辑校验成功后，再调用银行接口的支付接口
        flag = bank_interface.clean_pay_interface(login_user, cost)
        if flag:
            msg = f'用户：[{login_user}] 支付[{cost}元]成功,购物车已成功清空~~~~'

            shop_logger.info(msg)

            return True, msg

        return False, f"支付失败，还剩余额为：[{user_dic['balance']}元]"

    return False, f'当前用户的购物车为空，请添加购物车！'








